<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input clearable @clear="load" style="width: 200px;margin-left: 5px" v-model="data.name"
                placeholder="请输入名称查询" prefix-icon="Search"></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="load">查 询</el-button>
      <el-button type="info" style="margin-left: 5px" @click="reset">重 置</el-button>
    </div>
    <div v-if="data.user.role==='ADMIN'" class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger" @click="deleteBatch">批量删除</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px; width: 100%;">
      <el-table max-height="500"
          :data="data.tableData" style="width: 100%" @selection-change="handleSelectionChange"
          :header-cell-style="{color:'#333',backgroundColor:'#eaf4ff'}"
      >
        <el-table-column v-if="data.user.role==='ADMIN'" type="selection" width="55"/>
        <el-table-column prop="examName" label="考试名称"/>
        <el-table-column prop="examTime" label="考试时间"/>
        <el-table-column prop="details" label="考试说明"/>
        <el-table-column label="操作" width="100px" v-if="data.user.role==='ADMIN'">
          <template #default="scope">
            <el-button type="primary" icon="edit" circle @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" icon="delete" circle @click="del(scope.row.examId)"></el-button>

          </template>
        </el-table-column>

        <!--      <el-table-column prop="address" label="地址" width="180"/>-->
      </el-table>
    </div>
    <div class="card">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total,sizes, prev, pager, next,jumper"
          :page-sizes="[5, 20, 30, 40, 50, 100]"
          :total="data.total"
          @size-change="load"
          @current-change="load"/>
    </div>

    <el-dialog v-model="data.adminFormVisible" title="考试信息" width="500" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px" status-icon
               style="padding: 20px 30px 20px 0">
        <el-form-item prop="examName" label="考试名称">
          <el-input v-model="data.form.examName" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="说明">
          <el-input
              v-model="data.form.details"
              autosize
              type="textarea"
              autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker
              v-model="data.form.examTime"
              type="date"
              placeholder="请选择时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.adminFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import request from "@/utils/request";
import {reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || "{}"),
  name: null,
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  adminFormVisible: false,
  form: {},
  rules: {
    examName: [{required: true, message: '请填写名称', trigger: 'blur'}],
  },
  rows: []
})

const formRef = ref()
const load = () => {
  request.get('/exams/page', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
    }
  }).then(res => {
    if (res.code === '200') {
      // ElMessage.success('请求成功')
      data.tableData = res.data.records
      data.total = res.data.total
    } else {
      ElMessage.error(res.msg)
    }
  })
}
load()
const reset = () => {
  data.name = null
  data.username = null
  load()
}

const handleAdd = () => {
  data.adminFormVisible = true
  data.form = {}
}

const add = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.post('/exams/add', data.form).then(res => {
        if (res.code === '200') {
          data.adminFormVisible = false
          ElMessage.success('新增成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))//深度拷贝数据
  data.adminFormVisible = true
}

const update = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.put('/exams/update', data.form).then(res => {
        if (res.code === '200') {
          data.adminFormVisible = false
          ElMessage.success('修改成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const save = () => {
  data.form.examId ? update() : add()
}

const del = (id) => {
  ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/exams/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
  })
}

const handleSelectionChange = (rows) => {
  data.rows = rows
}

const deleteBatch = () => {
  if (data.rows.length === 0) {
    ElMessage.warning('请选择数据')
    return
  }
  // 只提取需要的ID列表，减少数据传输
  const ids = data.rows.map(row => row.examId)
  ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.post('/exams/deleteBatch', ids).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
  })
}

</script>

<style scoped>

</style>